package com.treetao.union.mall.api.controller;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.extension.service.IService;
import com.google.common.collect.Maps;
import com.treetao.union.db.model.MallCoupon;
import com.treetao.union.db.model.vo.RestResponse;
import com.treetao.union.db.service.MallCouponService;
import com.treetao.union.mall.api.base.BaseCURDController;
import com.treetao.union.mall.api.vo.req.ReqParam;

/**
 * 优惠券
 * 
 * @Author devm
 * @date 2020年5月27日
 * @see https://gitee.com/devm/devm-mall-server
 */
@RestController
@RequestMapping("/mall/coupon")
public class MallCouponController extends BaseCURDController {
	@Autowired
	private MallCouponService couponService;

	@Override
	protected IService<MallCoupon> getCommonService() {
		return couponService;
	}

	@GetMapping(list)
	@Override
	protected RestResponse list() {
		List<MallCoupon> coupons = couponService.getCanGetAvaliableCoupons();
		if(coupons!=null) {
			Long userId = getWxuidFromToken();
			for(MallCoupon cou : coupons) {
				boolean received = couponService.isReceivedCoupon(userId, cou.getId());
				Map<String,Object> exts = Maps.newHashMap();
				exts.put("received", received);
				cou.setExts(exts);
			}
		}
		return RestResponse.success(coupons);
	}
	
	/**
	 * 领取优惠券
	 * @return
	 */
	@PostMapping("receive")
	public RestResponse receive(@RequestBody ReqParam param) {
		Long couponId = param.getLong("couponId", false);
		return RestResponse.success(couponService.receiveCoupon(getWxuidFromToken(), couponId));
	}

	/**
	 * 我的优惠券
	 * @return
	 */
	@GetMapping("mycoupons")
	public RestResponse mycoupons() {
		ReqParam param = getMappingReqParam();
		String type = param.get("type");
		if("normal".equals(type)) {
			Double max = param.getDouble("max");
			return RestResponse.success(couponService.getMyCanUseCoupons(getWxuidFromToken(),max));
		} else if("used".equals(type)) {
			return RestResponse.success(couponService.getMyUsedCoupons(getWxuidFromToken()));
		} else if("overdate".equals(type)) {
			return RestResponse.success(couponService.getMyOverdateCoupons(getWxuidFromToken()));
		}
		return RestResponse.failure("无效type");
	}
}
